package com.dianxin.farm.api;

import com.alibaba.fastjson.JSONObject;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


import com.dianxin.farm.entity.Verycode;
import com.dianxin.farm.mapper.bill.VerycodeMapper;
import com.dianxin.farm.request.sms.CheckCodeRequest;
import com.dianxin.farm.request.sms.SendMessageRequest;
import com.dianxin.farm.util.exception.UserOperationException;
import com.dianxin.farm.util.util.Assert;
import com.dianxin.farm.util.util.DateUtil;
import com.dianxin.farm.util.util.StringUtil;
import com.dianxin.farm.util.web.ApiResponse;
import com.dianxin.farm.util.web.ApiResponseUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping(value = "/sms", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
@Api(description = "发送短信验证么")
public class SmsController {


    private static final String key="LTAI4GK5TiP2PaY2LYQv1iyy";
    private static final String secreat="5duRhaZFBqufZ3UT4x2jb3nORISPtB";
    private static final Logger logger = LoggerFactory.getLogger(SmsController.class);
    @Resource
    private VerycodeMapper verycodeMapper;

    @RequestMapping(value = "/send")
    @ResponseBody
    @ApiOperation("发送短信验证码,返回短信记录id，登录验证时候请传入此id")
    @Transactional
    public ApiResponse<Map<String, Integer>> createBill(@Valid @RequestBody SendMessageRequest request) {
        String phone = request.getPhone();
        String code = StringUtil.getVerifyCode();

        Verycode verycode = new Verycode();
        verycode.setCreateTime(LocalDateTime.now());
        verycode.setPhone(phone);
        verycode.setCodeType(1);
        verycode.setVerycode(code);
        verycodeMapper.insert(verycode);
        Integer id = verycode.getId();
        Map<String, Integer> map = new HashMap<>();
        map.put("id", id);
        Boolean status = sendMessage(phone, code);
        if (status == true) {

            return ApiResponseUtils.success(map);
        } else {
            return ApiResponseUtils.failure();
        }
    }

    @RequestMapping(value = "/checkCode")
    @ResponseBody
    @ApiOperation("校验短信验证码，六十秒有效")
    @Transactional
    public ApiResponse<Map<String, String>> checkCode(@Valid @RequestBody CheckCodeRequest request) {
        String phone = request.getPhone();
        String code = request.getCode();
        Integer id =request.getId();
        Assert.notNull(id,"验证码无效");
        QueryWrapper wrapper=new QueryWrapper();
        Date now=new Date();
        Date sixBefore= DateUtil.addSecond(now,-60);
        wrapper.eq("phone",phone);
        wrapper.eq("id",id);
        wrapper.eq("verycode",code);
        wrapper.gt("create_time",sixBefore);
        wrapper.orderByDesc("create_time");
        wrapper.last("limit 1");
        Verycode verycode=verycodeMapper.selectOne(wrapper);
        if (verycode==null){
            throw new UserOperationException("短信验证码已失效，请重新验证");
        }
        Map<String,String> map=new HashMap<>();
        map.put("result","验证成功");

        return ApiResponseUtils.success(map);

    }


    public static void main(String[] args) {
        sendMessage("18168516238", "123456");
    }

    public static Boolean sendMessage(String phone, String code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", key, secreat);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "高家庄生态餐厅");
        request.putQueryParameter("TemplateCode", "SMS_206550578");
        JSONObject object = new JSONObject();
        object.put("code", code);
        request.putQueryParameter("TemplateParam", object.toJSONString());
        Boolean status = false;
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject result = (JSONObject) JSONObject.parse(response.getData());
            String sendResponse = (String) result.get("Code");
            if (sendResponse.equals("OK")) {
                status = true;
            } else {
                logger.info(phone + "短信发送失败" + result.toJSONString());
            }


            // {"Message":"OK","RequestId":"42ED1C54-F60F-414F-87F0-1CEAC3D8DDFB","BizId":"967220899128023347^0","Code":"OK"}
            System.out.println(response.getData());


        } catch (ServerException e) {
            logger.info("阿里服务异常", e);
        } catch (ClientException e) {
            logger.info("阿里sdk异常", e);
        }
        return status;
    }
}
